<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";

type Pagination = {
  pageSize: number;
  pageNum: number;
};

const props = defineProps<{
  modelValue?: any;
  columns: { prop: string; label: string }[];
  getDataList: (params: Pagination) => Promise<{ list: any[]; total: number }>;
}>();
const emit = defineEmits(["update:modelValue"]);
const dataList = ref<any[]>([]);
const loading = ref(false);
const haveMore = ref(true);
const pagination = reactive<Pagination>({
  pageSize: 10,
  pageNum: 0
});

const loadNext = () => {
  if (loading.value || !haveMore.value) return;
  loading.value = true;
  pagination.pageNum++;
  props
    .getDataList(pagination)
    .then(res => {
      if (res.list.length < pagination.pageSize) {
        haveMore.value = false;
      }
      dataList.value.push(...res.list);
    })
    .finally(() => {
      loading.value = false;
    });
};
const onClick = (row: any) => {
  emit("update:modelValue", row);
};
onMounted(() => {
  loadNext();
});
</script>

<template>
  <el-table v-el-table-infinite-scroll="loadNext" :data="dataList" border>
    <el-table-column
      v-for="col in props.columns || []"
      :key="col.prop"
      :prop="col.prop"
      :label="col.label"
    >
      <template #default="{ row }">
        <span @click="onClick">{{ row[col.prop] }}</span>
      </template>
    </el-table-column>
  </el-table>
</template>
<style lang="scss" scoped></style>
